﻿/**
 * 獲取应用程序域公共類
 * 
 * @author LuoDong
 * @email luo4521@online.net.tw
 */
package com.kucooler.common.utils
{
	import flash.utils.Dictionary;
	import flash.system.ApplicationDomain;
	
	public class  AppLibary
	{
		private var _dic : Dictionary = new Dictionary();
		private static var _instance : AppLibary;
		
		public function AppLibary() : void 
		{
			if (_instance != null) {
				throw ("[AppLibary] 為單例類!");
			}			
		}
		
		public static function getInstance() : AppLibary {
			if ( _instance == null) {				
				_instance = new AppLibary();
			}
			return _instance;
		}
			
		
		/**
		 * 获取某个应用程序域下的类
		 * @param	r_className String
		 * @param	r_app ApplicationDomain
		 * @return
		 */
		public function getClass(r_className : String , r_app : ApplicationDomain = null) : Class		
		{			
			if (r_app == null) {
				r_app = ApplicationDomain.currentDomain;								
			}	
			if (this._dic[r_app] != null) {
				var _ref_class = this._dic[r_app][r_className] as Class;
				if (_ref_class != null) {
					return _ref_class;					
				}				
			}else {
				var _obj : Object = new Object();
				this._dic[r_app] = _obj;
			}
			var _class : Class;
			var _class_obj :Object = { };
			while (r_app) {				
				try{
					_class = r_app.getDefinition(r_className) as Class;				    
					_obj[r_className] = _class;
					this._dic[r_app] = _obj;	
					break;
				}catch (e : ReferenceError){
					trace("#[" + r_className + "] undefine!");	
					_class = null
				}
				r_app = r_app.parentDomain;
			}
			if (_class == null) {
				for (var _key in this._dic) {					
					if (this._dic[_key][r_className] != null) {
						return this._dic[_key][r_className] as Class;						
					}
				}
			}
			return _class;				
		}
		
	}
	
}
